package com.jobs.producer0.demo;

import com.jobs.common.factory.RabbitMqUtils;
import com.rabbitmq.client.Channel;

import java.nio.charset.StandardCharsets;

/**
 * 发布确认模式，
 * 1、单个确认
 * 2、批量确认
 * 3、异步批量确认
 * @author xdh
 * */

public class ConfirmMessage {

    /**
     *  批量发消息的个数
     */
    public static final int MESSAGE_COUNT = 1000;
    public static final String queueName = "Confirm_queue";

    public static void main(String[] args) throws Exception {
        // 1、单个确认
        // 发布1000个单独确认消息，耗时567ms
        ConfirmMessage.publishMessageIndividually();

    }

    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        // 开启发布确认
        channel.confirmSelect();

        channel.queueDeclare(queueName,true,false,false,null);

        // 开始时间
        long begin = System.currentTimeMillis();

        // 批量发消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + " 消息";
            channel.basicPublish("",queueName,null,message.getBytes(StandardCharsets.UTF_8));
            // 单个消息马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag){
                System.out.println("消息发送成功");
            }
        }

        // 结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个单独确认消息，耗时"+ (end - begin) + "ms");
    }
}
